package com.novel.service.impl.review;

import com.novel.config.RedissonHelper;
import com.novel.entiy.Chapter;
import com.novel.entiy.Novel;
import com.novel.entiy.dto.ReviewDTO;
import com.novel.mapper.ChapterMapper;
import com.novel.mapper.NovelMapper;
import com.novel.service.NovelService;
import com.novel.service.ReviewService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author tanghao
 * @date 2022/4/19
 */
@Slf4j
@Service
public class ChapterEditReviewServiceImpl implements ReviewService {

    @Resource
    private RedissonHelper redissonHelper;

    @Resource
    private NovelMapper novelMapper;

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private NovelService novelService;

    /**
     * 同意审批
     *
     * @param reviewDTO 审批参数
     */
    @Override
    public void agreeReview(ReviewDTO reviewDTO) {
        log.info("章节编辑同意审批 {}", reviewDTO);
        //缓存丢了 直接更改状态为发布
        Chapter chapter = chapterMapper.selectById(reviewDTO.getMainId());
        chapter.setStatus(1);
        chapterMapper.updateById(chapter);
        novelService.updateNovel(chapter);
        //删除缓存
        redissonHelper.clearBucket("edit-novel" + reviewDTO.getMainId());
    }

    /**
     * 拒绝审批
     *
     * @param reviewDTO 审批参数
     */
    @Override
    public void rejectReview(ReviewDTO reviewDTO) {
        log.info("小说编辑审批不通过 {}", reviewDTO);
        Object value = redissonHelper.getValue("edit-chapter" + reviewDTO.getMainId());
        if (ObjectUtils.isEmpty(value)) {
            //缓存丢了 直接更改状态为发布
            Chapter chapter = chapterMapper.selectById(reviewDTO.getMainId());
            chapter.setStatus(1);
            chapterMapper.updateById(chapter);
        } else {
            //修改回编辑前
            Chapter chapter = (Chapter) value;
            chapterMapper.updateById(chapter);
        }

        //删除缓存
        redissonHelper.clearBucket("edit-novel" + reviewDTO.getMainId());
    }
}
